package ltd.dujiabao.mavenLocalInstaller.util;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Objects;

/**
 * @author : DuJiabao
 * @Project : mavenLocalInstaller
 * @Time : 2021/9/28 23:52
 * @Desc :
 */
public class PathUtils {
    /**
     * 获取当前resource在target中的绝对路径
     */
    public static String getPath() {
        return Objects.requireNonNull(PathUtils.class.getResource("/")).getPath();
    }

    /**
     * 获取当前resource在target中的绝对路径
     */
    public static String getPath(String relativePath) {
        return getPath() + relativePath;
    }

    /**
     * 确保路径一定以分隔符结尾
     */
    public static String ensureEndWithSeparator(String path) {
        if (!path.endsWith(File.separator)) {
            path += File.separator;
        }
        return path;
    }

    /**
     * rm -rf path
     *
     * @param path 绝对路径
     */
    public static void removeRf(String path) {
        removeRf(Paths.get(path));
    }

    /**
     * rm -rf path
     *
     * @param path 绝对路径
     */
    public static void removeRf(Path path) {
        if (!Files.exists(path)) {
            System.out.println("Cannot find " + path + "!");
            return;
        }

        // 先清空文件夹内容
        if (Files.isDirectory(path)) {
            try {
                Files.list(path).forEach(PathUtils::removeRf);
                System.out.println("Finish empty directory " + path);
            } catch (IOException e) {
                System.out.println("Occur exception when delete directory " + path);
                e.printStackTrace();
            }
        }

        try {
            Files.delete(path);
            System.out.println("Finish delete " + path);
        } catch (IOException e) {
            System.out.println("Occur exception when delete " + path);
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        System.out.println(PathUtils.getPath("fastjson-1.2.78.jar"));
    }
}
